package com.wzx.selfuse.controller;

import com.wzx.selfuse.entity.User;
import com.wzx.selfuse.exception.BusinessException;
import com.wzx.selfuse.service.UserService;
import com.wzx.selfuse.vo.AjaxEntityResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//表示控制层，且被spring管理，注入到容器中
@Controller
//表示一级路径，代替servlet，以后直觉请求/user即可
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("index")
    public String getUser(Model model){
       /* List<User> users = userService.getUsers();
        model.addAttribute("users", users);*/
        return "index";
    }


    @RequestMapping("/loginAjax")
    @ResponseBody
    public AjaxEntityResult<User> filterAjax(String username, String password, HttpServletRequest request) throws BusinessException {

        List<User> userByUserName = userService.getUserByUserName(username);

        AjaxEntityResult<User> ajaxEntityResult = new AjaxEntityResult<User>();

        if (userByUserName.size() > 1) {
            ajaxEntityResult.setCode(400);
            ajaxEntityResult.setMsg("user is not only one");
            return ajaxEntityResult;
        }

        if (userByUserName.size() == 1) {
            if (password.equals(userByUserName.get(0).getPassword())) {
                request.getSession().setAttribute("user", userByUserName.get(0).getUsername());
                System.out.println("success");
                ajaxEntityResult.setCode(200);
                ajaxEntityResult.setMsg("login");
                return ajaxEntityResult;
            } else {
                ajaxEntityResult.setCode(400);
                ajaxEntityResult.setMsg("error password");
                return ajaxEntityResult;
            }
        }
        return ajaxEntityResult;
    }


   /* @RequestMapping("/select")
    public String selectUser(){
        List<User> users = userService.selectUser();

    }*/
}
